﻿using MCPlatform.UI.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using MCPlatform.Models;
using MCPlatform.Shared.Enums;
using MCPlatform.ViewModels.Shell;
using System.Windows;
using Caliburn.Micro;
using MCPlatform.UI.Controls.Views;
using System.Windows.Input;
using Panuon.WPF;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using Panuon.WPF.UI;
using System.Threading;
using MCPlatform.MotionLib.Base.AssitantClass;
using MCPlatform.MotionLib.Base.Environment;
using MCPlatform.Builder.WorkStation.StationEvents.Product;
using MCPlatform.ViewModels.Product;
using MCPlatform.Components;
using System.Windows.Threading;
using System.Diagnostics;
using MCPlatform.Views.Shell;
using System.Runtime.ConstrainedExecution;
using MCPlatform.Shared.Enums.Modes;
using System.ComponentModel;
using System.Reflection;
using MCPlatform.UI.Resources.Languages;

namespace MCPlatform.ViewModels
{
    public class ShellViewModel :ViewModelBase,IHandle<ProductToShellEvent>
    {

        #region Fields

        private bool _isFirstScan = true;
      

        private Stopwatch stopwatch = new Stopwatch();

        private static string _lightTheme = "\uE9C8";

        private static string _darkTheme = "\uE9C6";

        #endregion

        #region ctor

        public ShellViewModel()
        {
            //获取激活管理实例
            ActivationManager = ActivationManager.GetInstance();
            ActivateViewModel = new ActivateViewModel();         
            CommunicateViewModel = new CommunicateViewModel();
            LogViewModel = new LogViewModel();
            HomeViewModel = new HomeViewModel();         
            DataTableViewModel = new DataTableViewModel();
            AlarmViewModel = new AlarmViewModel();
            SettingsViewModel = new SettingsViewModel();
            UserLoginViewModel = new UserLoginViewModel();
            UserLoginViewModel.LoginSuccess += UserLoginViewModel_LoginSuccess;
            ProductViewModel.SaveEvent += ProductViewModel_SaveEvent;
            ProductViewModel.DeleteEvent += ProductViewModel_DeleteEvent;
            ProductViewModel.RenameEvent += ProductViewModel_RenameEvent;


            Load();
           // CheckActivationStatus();

        }

       

      



        #endregion

        #region events define

        public static event System.Action? ClosingWindowEvent;

        public static event System.Action<LanguageEnum>? ChangeLanguageEvent;


        #endregion


        #region Properties
        public ActivationManager ActivationManager { get; set; }

        #region SelectedMainMenuIndex

        public int SelectedMainMenuIndex { get => _selectedMainMenuIndex; set => Set(ref _selectedMainMenuIndex, value); }
        private int _selectedMainMenuIndex;

        #endregion

        public string UserName
        { 
            get => _userName;
            set
            {
                Set(ref _userName, value);
                User = value;
            }
        }
        private string _userName = "Operator";

        public LanguageEnum Language
        {
            get => _language;
            set
            {
                Set(ref _language, value);

                ChangeLanguage(Common.GetEnumDescription(value));

                Culture = value;

                ChangeLanguageEvent?.Invoke(Culture);

                var start = LocalizationHelper.GetString(Culture, "Start");
            }
        }
        private LanguageEnum _language;


        /// <summary>
        /// 产品类型集合
        /// </summary>
        public ObservableCollection<ProductModel> ProductModels { get; set; } = new ObservableCollection<ProductModel>();


        /// <summary>
        /// 选中项
        /// </summary>
        public ProductModel SelectedProductModel
        {
            get => _SelectedProductModel;
            set
            {
                Set(ref _SelectedProductModel, value);
                ProductionType = value.ControlName;

            }
        }
        private ProductModel _SelectedProductModel = new ProductModel();


        public ProductModel SelectedItem
        {
            get { return _selectedItem; }
            set
            {
             
                if (value is null)
                {
                    return;
                }
                Set(ref _selectedItem, value);               

                SelectedProductModel = value;
                SetAllProductUnselected();
                SelectedProductModel.IsLastSelected = true;

                if (_isFirstScan)
                {
                    _isFirstScan = false;
                    return;
                }
                Save();
            }
        }
        private ProductModel _selectedItem = new ProductModel();



        public string ThemeContent
        {
            get { return _themeContent; }
            set
            {
               
                Set(ref _themeContent, value);
               
            }
        }
        private string _themeContent = _lightTheme;



        #region SelectedViewIndex

        public int SelectedViewIndex { get => _selectedViewIndex; set => Set(ref _selectedViewIndex, value); }
        private int _selectedViewIndex = 0;


        public string ProductTimer { get => _ProductTimer; set => Set(ref _ProductTimer, value); }
        private string _ProductTimer = "00:00:00";

        public string TotalTimer { get => _TotalTimer; set => Set(ref _TotalTimer, value); }
        private string _TotalTimer = "00:00:00";

        #endregion


        #region ViewModels

        public ActivateViewModel ActivateViewModel { get; }
        public HomeViewModel HomeViewModel { get; }

        public CommunicateViewModel CommunicateViewModel { get; }

        public DataTableViewModel DataTableViewModel { get;  }

        public LogViewModel LogViewModel { get;  }

        public SettingsViewModel SettingsViewModel { get;  }

        public AlarmViewModel AlarmViewModel { get;}

        public UserLoginViewModel UserLoginViewModel { get; }
        #endregion

        #endregion

        #region Event Handler
        protected override  Task OnDeactivateAsync(bool close,CancellationToken cancellationToken)
        {
           
            ClosingWindowEvent?.Invoke();

            return base.OnDeactivateAsync(close, cancellationToken);

        }


     

        public void OnMainMenuSelectionChanged()
        {         
            if (SelectedMainMenuIndex != -1)
            {

                SelectedViewIndex = SelectedMainMenuIndex;
            }

        }




        private void ProductViewModel_RenameEvent(string oldName, string rename)
        {

            //先判断是否有这个产品
            foreach (ProductModel pm in ProductModels)
            {
                if (pm.ControlName.Equals(oldName))
                {
                    pm.ControlName = rename;
                    return;
                }
            }

        }

        private void ProductViewModel_DeleteEvent(ProductModel productModel)
        {
            //先判断是否有这个产品
            foreach (ProductModel pm in ProductModels)
            {
                if (pm.ControlName.Equals(productModel.ControlName))
                {
                    ProductModels.Remove(pm);
                    return;
                }
            }
        }

        private void ProductViewModel_SaveEvent(ProductModel productModel)
        {


            //先判断是否有这个产品
            foreach (ProductModel pm in ProductModels)
            {
                if (pm.ControlName.Equals(productModel.ControlName))
                {
                    Common.AutoMapProperties(productModel, pm);
                    //ProductModels.Remove(pm);
                    //ProductModels.Add(productModel);

                    SelectedItem = pm;
                    //  SelectedItem = productModel;

                    return;
                }
            }


            //没有就新增并更新

            ProductModels.Add(productModel);
            SelectedItem = productModel;


        }


        #endregion


        #region Methods

        public void Exit()
        {
            UserName = "Operator";
        }

        public void Change()
        {
            WindowManager.ShowDialogAsync(UserLoginViewModel);
            


        }

        private void UserLoginViewModel_LoginSuccess(string obj)
        {
            UserName = obj;
        }

        public void ChangeLanguage(string cultrue)
        {

            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                var targetDictionary = dictionary.MergedDictionaries
                    .FirstOrDefault(mer => mer.Source.OriginalString.Contains(cultrue));

                if (targetDictionary != null)
                {
                    dictionary.MergedDictionaries.Remove(targetDictionary);
                    dictionary.MergedDictionaries.Add(targetDictionary);
                    Application.Current.Resources.MergedDictionaries.Remove(dictionary);
                    Application.Current.Resources.MergedDictionaries.Add(dictionary);

                    break;
                }
            }



        }


      

        public void Load()
        {
            var productConfigs = ReadConfigData.GetParaConfigs<ProductModel>(Paths.ProductConfigPaths);

            if (productConfigs != null)
            {
                ProductModels = new ObservableCollection<ProductModel>(productConfigs);
                SearchLastSelecteItem();
            }
                    
        }

        public void Save()
        {
            if (ProductModels.Count > 0)
            {
                SaveConfigData.SaveConfig<ProductModel>(Paths.ProductConfigPaths, ProductModels.ToArray());

            }
        }

        public void Activate()
        {
            WindowManager.ShowDialogAsync(ActivateViewModel);
        }


        /// <summary>
        /// 设置全部为未选中状态
        /// </summary>
        private void SetAllProductUnselected()
        {
            if (ProductModels.Count > 0)
            {
                foreach (var product in ProductModels)
                {
                    product.IsLastSelected = false;
                }
            }
        }

        /// <summary>
        /// 查找最后一个选中的产品
        /// </summary>
        private void SearchLastSelecteItem()
        {
            if (ProductModels.Count > 0)
            {
                foreach (var product in ProductModels)
                {
                    if (product.IsLastSelected)
                    {
                        SelectedProductModel = product;
                        SelectedItem = SelectedProductModel;
                        break;
                    }
                }
            }
        }

        public Task HandleAsync(ProductToShellEvent message, CancellationToken cancellationToken)
        {
            Load();
            return Task.CompletedTask;
        }

        public void SwitchTheme()
        {
            if (ThemeContent.Equals(_lightTheme))
            {
                ThemeContent = _darkTheme;
                ChangeTheme("Dark");
                return;
            }

            ThemeContent = _lightTheme;

            ChangeTheme("Light");
        }


        public void ChangeTheme(string theme)
        {

            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {


                if (dictionary.Source!= null && dictionary.Source.ToString().Contains(theme))
                {
                  
                    Application.Current.Resources.MergedDictionaries.Remove(dictionary);
                    Application.Current.Resources.MergedDictionaries.Add(dictionary);

                    break;
                }
            }



        }


        #endregion

    }
}
